package com.spider.sql.controller;

import com.spider.sql.dao.UserDao;
import com.spider.sql.pojo.InjectionData;
import com.spider.sql.pojo.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/")
public class SqlInjectionController {
    private final UserDao userDao = new UserDao();

    @GetMapping("/login")
    public User login(@RequestParam String username, @RequestParam String password, HttpSession session) throws SQLException, ClassNotFoundException {
        User user = userDao.getUserByUsernameAndPassword(username, password);
        // 存储注入参数、时间、结果和接口信息到会话中
        storeInjectionData("/login", username, password, user, session);
        return user;
    }

    @GetMapping("/search")
    public List<User> search(@RequestParam String username, HttpSession session) throws SQLException, ClassNotFoundException {
        List<User> users = userDao.searchUsersByUsername(username);
        // 存储注入参数、时间、结果和接口信息到会话中
        storeInjectionData("/search", username, null, users, session);
        return users;
    }

    private void storeInjectionData(String endpoint, String username, String password, Object result, HttpSession session) {
        // 添加时间戳
        String timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        // 创建记录对象
        InjectionData data = new InjectionData(endpoint, username, password, result, timestamp);
        // 将记录对象存储到会话中的列表
        List<InjectionData> injectionDataList = (List<InjectionData>) session.getAttribute("injectionDataList");
        if (injectionDataList == null) {
            injectionDataList = new ArrayList<>();
        }
        injectionDataList.add(data);
        session.setAttribute("injectionDataList", injectionDataList);
    }


}
